<template>
  <a-modal
    v-model:visible="modelValue"
    :title="props.title"
    title-align="start"
    :mask-closable="false"
    :unmount-on-close="true"
    draggable
    class="modal-dialog-wrapper"
    :width="width || 'auto'"
    @before-open="emit('beforeOpen')"
    @close="onCancel"
  >
    <div
      class="modal-dialog-content"
      :style="{
        height: isNumberValue(props.contentHeight)
          ? `${props.contentHeight}px`
          : props.contentHeight,
      }"
    >
      <slot></slot>
    </div>
    <template #footer>
      <slot v-if="$slots.footer" name="footer"></slot>
      <div v-else>
        <a-space v-if="confirmBtn">
          <a-button @click="onCancel">取消</a-button>
          <a-button type="primary" :loading="btnLoading" @click="onConfirm">{{
            props.okText ? props.okText : '确定'
          }}</a-button>
        </a-space>
        <a-space v-else>
          <a-button @click="onCancel">关闭</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { useVModel } from '@vueuse/core';

  import { isNumberValue } from '@/utils/is';

  const props = defineProps({
    modelValue: Boolean,
    title: {
      type: String,
      default: '操作',
    },
    contentHeight: {
      type: [String, Number],
    },
    width: {
      type: [Number, String],
      default: '30vw',
    },
    confirmBtn: {
      type: Boolean,
      default: true,
    },
    okText: {
      type: String,
    },
    btnLoading: {
      type: Boolean,
      default: false,
    },
    fullscreen: Boolean,
  });
  const emit = defineEmits([
    'confirm',
    'cancel',
    'update:modelValue',
    'beforeOpen',
  ]);

  const params = ref<object>({});
  const modelValue = useVModel(props, 'modelValue', emit) as Ref<boolean>;
  const { confirmBtn } = toRefs(props);

  const { btnLoading } = toRefs(props);

  const width = computed(() => {
    return isNumberValue(props.width) ? `${props.width}px` : props.width;
  });

  const onConfirm = () => {
    emit('confirm', params.value);
  };
  const onCancel = () => {
    modelValue.value = false;
    emit('cancel');
    emit('update:modelValue', false);
  };
</script>

<style>
  .modal-dialog-content {
    max-height: 80vh;
    min-width: v-bind(width);
    overflow-x: hidden;
  }
</style>
